import { memo, useEffect, useState } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Link, useParams } from 'react-router-dom';
import {
  Alert,
  Button,
  Descriptions,
  message,
  Modal,
  PageHeader,
  Steps,
} from 'antd';
import {
  resOrdersCancel,
  resOrdersConfirm,
  resOrdersDetail,
} from '@/services/orders';
import { useRequest } from 'ahooks';
import ConfirmOrders from '@/pages/Order/OrdersDetail/components/ConfirmOrders';
import ExpressInfo from '@/pages/Order/OrdersDetail/components/ExpressInfo';
import OrdersComment from '@/pages/Order/OrdersDetail/components/OrdersComment';
import OrdersTable from '@/pages/Order/OrdersDetail/components/OrdersTable';
import ReceiptOrders from '@/pages/Order/OrdersDetail/components/ReceiptOrders';
import { formatTime } from '@/utils/format';

const createSteps = (
  refresh: Function,
  nextStep: Function,
  data?: API.OrdersDetailResult
) => {
  return [
    {
      title: '确定下单',
      content: <ConfirmOrders refresh={refresh} />,
    },
    {
      title: '付款到支付宝',
      content: (
        <div className={'py-4'}>
          <Alert
            message={'等待商家发货'}
            description={'已经付款成功，等待商家发货中...'}
            type={'success'}
            className={'text-center'}
          />
        </div>
      ),
    },
    {
      title: '商家发货',
      content: (
        <div className={'mt-4 px-2 text-right '}>
          <Button
            type={'primary'}
            onClick={() => {
              Modal.confirm({
                title: '确定收货',
                content: '是否确定收货？',
                okText: '确定',
                cancelText: '取消',
                type: 'success',
                onOk: () => {
                  data &&
                    resOrdersConfirm(data.id).then(() => {
                      message.success('收货成功');
                      refresh();
                    });
                },
              });
            }}
          >
            确定收货
          </Button>
        </div>
      ),
    },
    {
      title: '确认收货',
      content: <ReceiptOrders nextStep={nextStep} />,
    },
    {
      title: '评价',
      content: data && <OrdersComment refresh={refresh} source={data} />,
    },
  ];
};

const OrdersDetail: FC<PropsWithChildren<{}>> = () => {
  const params = useParams();
  const { data, loading, refresh } = useRequest(resOrdersDetail, {
    defaultParams: [Number(params.id)],
  });

  const [current, setCurrent] = useState(0);
  useEffect(() => {
    console.log(data);
    setCurrent(
      data?.status
        ? data?.comment && data?.comment.length > 0 && data.status === 4
          ? data?.status
          : data?.status - 1
        : 0
    );
  }, [data]);

  const nextStep = () => {
    setCurrent((preState) => {
      return preState < 5 ? preState + 1 : preState;
    });
  };

  const steps = createSteps(refresh, nextStep, data);

  return (
    <section className={'w-[1200px] px-16 pt-8 pb-4 m-auto'}>
      <section className={'bg-white rounded-2xl pb-12'}>
        {data?.status !== 5 && (
          <div className={'py-6 px-12'}>
            <Steps current={current}>
              {steps.map((item) => (
                <Steps.Step key={item.title} title={item.title} />
              ))}
            </Steps>
          </div>
        )}
        <div className={'py-4 px-8'}>
          <Descriptions title="订单信息">
            <Descriptions.Item label="收货地址">
              <div className={'space-x-1'}>
                {[
                  <span key={1}>{data?.address.province}</span>,
                  <span key={2}>{data?.address.city}</span>,
                  <span key={3}>{data?.address.county}</span>,
                  <span key={4}>{data?.address.address}</span>,
                ]}
              </div>
            </Descriptions.Item>
            <Descriptions.Item label="订单编号">
              {data?.order_no}
            </Descriptions.Item>
            <Descriptions.Item label="支付宝交易号">
              {data?.trade_no}
            </Descriptions.Item>
            <Descriptions.Item label="支付时间">
              {data?.pay_time && data?.pay_time !== '0001-01-01T00:00:00Z' &&
                formatTime(data?.pay_time)}
            </Descriptions.Item>
            <Descriptions.Item label="收货人信息">
              <div className={'space-x-1'}>
                {[
                  <span key={1}>{data?.address.name}</span>,
                  <span key={2}>{data?.address.phone.slice(3)}</span>,
                ]}
              </div>
            </Descriptions.Item>
            <Descriptions.Item label="商家">
              <Link to={`/user_page/` + data?.orders_detail[0].goods.user_id}>
                {data?.orders_detail[0].goods.user?.name}
              </Link>
            </Descriptions.Item>
          </Descriptions>
        </div>
        {data?.status === 5 ? (
          <Alert
            showIcon
            message={'交易已关闭'}
            description={'交易过期或者已被取消'}
            className={'text-center'}
            type={'warning'}
          />
        ) : (
          <div className={'border-t px-6 py-4'}>{steps[current].content}</div>
        )}
        {data && data?.status > 2 && <ExpressInfo source={data} />}
        {data && (
          <div className={'p-8'}>
            <OrdersTable data={data} />
          </div>
        )}
      </section>
    </section>
  );
};

export default memo(OrdersDetail);
